// app.js
App({

  globalData:{
    MsgChange:"",
     task : {}
  },






  onLaunch() {
    var that = this
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录

    //在缓存读取用户信息
    var HasUserInfo = wx.getStorageSync('hasUserInfo')
    var Code = wx.getStorageSync('code')
    var userNickName = wx.getStorageSync('UserNickName')
    var userAvatarUrlr = wx.getStorageSync('UserAvatarUrlr')
    var token = wx.getStorageSync('token')

    //获取用户信息
    if (HasUserInfo&&Code&&userAvatarUrlr&&userNickName)
    {
      console.log(HasUserInfo)
      console.log(Code)
      console.log(userNickName)
      console.log(userAvatarUrlr)
      that.setData({
        UserNickName :  userNickName,
        UserAvatarUrlr : userAvatarUrlr,
        code : Code ,
        hasUserInfo : HasUserInfo
      })

  }



  var  MsgListData=[]

              if(wx.getStorageSync('token')!==""){

              //在线获取未接消息的列表
              wx.request({
                url: 'http://119.23.252.15:10004/synchronize',
                method:"POST",
                data:{
                  "token":wx.getStorageSync('token')
                },
                success(res){
                  console.log(wx.getStorageSync('token'))
                  console.log(res.data)
                  if(res.data.status==1){
                      MsgListData=res.data.data.msgList
                  }
        
                   
                }
              })
            }
        
            
              if(MsgListData.length>0){
              //对MsgListData进行循环获取未接受信息  
              for(var i=0 ; i<MsgListData.length ; i++)
              {
                
        
        
        
                console.log("接受未收信息中")
                //通过openid获取缓存若为空则设置缓存
                if(wx.getStorageSync(MsgListData[i].sender)=="")
                {
                  console.log("聊天缓存为空")
                  var chatMsg=[{
                    person:"yourside",
                    Msg:"以上为打招呼消息",
                    time:MsgListData[i].date-1
                        },
                  {
                    person:"yourside",
                    Msg:MsgListData[i].msg,
                    time:MsgListData[i].date
                  }
                        ] 
                }
            
                //若已有聊天缓存则将信息加入缓存
                else{
                  console.log("聊天缓存不为空")
                  var chatMsg=wx.getStorageSync(MsgListData[i].sender)
                  chatMsg.push({
                    person:"yourside",
                    Msg:MsgListData[i].msg,
                    time:MsgListData[i].date
                  })
                }
            
                //设置用户聊天缓存
                wx.setStorage({
                  data: chatMsg,
                  key: MsgListData[i].sender,
                  success(){
                    console.log("添加聊天信息成功")
                  }
                })
            
            
                  
                  //获取消息列表缓存若为空则创建
                  var msgListData = []
                  if(wx.getStorageSync('msgListData')=="")
                  {
                    wx.setStorage({
                      data: [],
                      key: 'msgListData',
                    })
                    msgListData = []
                    console.log("MsgListData为空")
                  }
                  else{
                  msgListData = wx.getStorageSync('msgListData')
                  console.log(msgListData)
                     }
            
            
                  //判断聊天队列是否有该用户记录有则更新信息没有则添加
                  let flag=false
  
                          //通过用户openid获取用户nickname和头像url
              // wx.request({
              //   url: 'http://119.23.252.15:10001/getUserInfoById?openid='+MsgListData[i].sender,
              //   // url: 'http://119.23.252.15:10001/getUserInfoById?openid=o8Usb5h-unx4bS-FKmPh2uyxq0Uc',
              //   method:"GET",
              //   success(res){
              //     console.log(res.data)
              //     var  counterNickName = res.data.data.userInfo.nickName
              //     var  counterUrl = res.data.data.userInfo.avatarUrl
              //      console.log("发送者是"+res.data.data.userInfo.nickName)
              //   }
              // })
  
                  for (let y = 0; y < msgListData.length&!flag; y++) {
                    if (msgListData[y].openid==MsgListData[i].sender){
                    msgListData[y].recentmessage=MsgListData[i].msg
                    msgListData[y].time=MsgListData[i].date
                    // msgListData[y].url=MsgListData[i].
                    // msgListData[y].nickname=counterNickName
                    wx.setStorage({
                      data: msgListData,
                      key: 'msgListData',
                    })
                    flag=true
                    console.log("修改信息成功")
                    }
                  }
              
                  if(!flag){

                    wx.request({
                      url: 'http://119.23.252.15:10001/getUserInfoById?openid='+MsgListData[i].sender,
                      // url: 'http://119.23.252.15:10001/getUserInfoById?openid=o8Usb5h-unx4bS-FKmPh2uyxq0Uc',
                      method:"GET",
                      success(res){
                    msgListData.push({
                          openid:MsgListData[i-1].sender,
                          url:res.data.data.userInfo.avatarUrl,
                          nickname:res.data.data.userInfo.nickName,
                          recentmessage:MsgListData[i-1].msg, 
                          time:MsgListData[i-1].date
                        },)

                                            //缓存聊天列表
                    wx.setStorage({key:'msgListData',data: msgListData,success(){
                      console.log("接受未接受信息并缓存成功")
                    }})

                         console.log("发送者是"+res.data.data.userInfo.nickName)
                        }
                    })


  
            
                    // this.sortArray(msgListData)
        

            
                  }

              //   }
              // })
                
                
              }
            }
        
          //   }
          // })



    



    //创建一个webSocket链接
    that.globalData.task= wx.connectSocket({
      // url: 'file:///C:/Users/25476/Documents/WeChat%20Files/wxid_kexcdp8hni2f22/FileStorage/File/2021-04/Chat1.html',
      url: 'ws://119.23.252.15:10003/chat/'+wx.getStorageSync('token'),
      // url: 'wx://localhost/chat/c6fbc5b95190a6f2aa705325d01a6d9e',
      header:{
        'content-type': 'application/json'
      },
      success(){
        console.log("链接成功")
      },
      fail(){
        console.log("链接失败")
      }
    })


    //检测webSocket链接情况
    that.globalData.task.onOpen(()=>{ console.log('链接成功！') })

    that.globalData.task.onClose(() =>{console.log("close")})

    
    //接受信息
    that.globalData.task.onMessage((res)=>{

      console.log("首页接收信息中")
      var resData =  JSON.parse(res.data)
      console.log(resData) 



      //接受到信息后判断与该用户是否有聊天记录 
      if (resData.type=="sendMsg"){

        var chatMsg = []
        var msgListData = []
  
        var counterNickNames = ""
        var counterUrls =  ""
  
        ////获取发送信息用户的nickname和头像url
          wx.request({
            url: 'http://119.23.252.15:10001/getUserInfoById?openid='+resData.sender,
            success(res){
               counterNickNames = res.data.data.userInfo.nickName
               counterUrls = res.data.data.userInfo.avatarUrl
            }
          })
        //没有就创建新的聊天记录缓存
          if(wx.getStorageSync(resData.sender)=="")
          {
              chatMsg=[{
                person:"yourside",
                Msg:"以上为打招呼消息",
                time:resData.date
                    }
                  ]

          }

          //有则读取原来聊天记录并添加新消息
          else{
          chatMsg=wx.getStorageSync(resData.sender)
          console.log(chatMsg)
              }
          //将接收的信息加入聊天记录中
          chatMsg.push({
          person:"yourside",
          Msg:resData.msg, 
          time:resData.date
            })

          //缓存聊天记录
          wx.setStorage({
            data: chatMsg,
            key: resData.sender, 
            success(){
              console.log("openid为"+resData.sender+"发送信息"+resData.msg) 
            }
          })


      //获取消息列表缓存若为空则创建
      if(wx.getStorageSync('msgListData')=="")
      {
        wx.setStorageSync('msgListData', [])
        msgListData = wx.getStorageSync('msgListData')
        console.log("msgListData为空")
      }
      else{
      msgListData = wx.getStorageSync('msgListData')
      console.log(msgListData)
         }


      //判断聊天队列是否有该用户记录有则更新信息没有则添加
      let flag=false
      for (let i = 0; i < msgListData.length; i++) {
        if (msgListData[i].openid==resData.sender){
        msgListData[i].recentmessage=resData.msg
        msgListData[i].time=resData.date
        msgListData[i].url=counterUrls
        msgListData[i].nickname=counterNickNames
        wx.setStorageSync('msgListData',msgListData)
        flag=true
        console.log("修改信息成功")
        }
      }
  
      //若没有该用户的聊天记录则将记录添加到消息列表中
      if(!flag){
        msgListData.push({
          openid:resData.sender,
          url:counterUrls,
          nickname:counterNickNames,
          recentmessage:resData.msg, 
          time:resData.date
        },)

        // this.sortArray(msgListData)

        //更新消息列表的缓存
        wx.setStorage({key:'msgListData',data: msgListData,success(){
          console.log("缓存消息成功")
        }})

      }



    }

      })


  },


  //发送信息
  sendSocketMessage: function (msg) {
    var that =this
    console.log(JSON.stringify(msg))
    if (that.globalData.task.readyState === 1) {     
      that.globalData.task.send({
        data: JSON.stringify(msg),
        success: function(res){
          console.log("发送成功")
        }
      }
      )
    } else {
      console.log("发送失败")
    }
  },


  
  // sortArray: function(List){
  //   for(var i = 1 ;i<List.length;i++){
  //     for(var y =0 ;y<List.length-1;y++){
  //       if(List[y].date<List[y+1].date){
  //         var obj=List[y]
  //         List[y]=List[y+1]
  //         List[y+1]=obj
  //       }
  //     }
  //   }
  // }


})
